package store.lunangangster.engine.impl.cmd;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import store.lunangangster.engine.impl.entity.DeploymentEntity;
import store.lunangangster.engine.impl.entity.ResourceEntity;
import store.lunangangster.engine.impl.interceptor.CommandContext;
import store.lunangangster.engine.impl.repository.DeploymentBuilderImpl;
import store.lunangangster.engine.repository.Deployment;

public class DeployCmd implements Command<Deployment> {

  private static final Logger log = LoggerFactory.getLogger(DeployCmd.class);

  protected DeploymentBuilderImpl deploymentBuilder;

  public DeployCmd(DeploymentBuilderImpl deploymentBuilder) {
    this.deploymentBuilder = deploymentBuilder;
  }

  @Override
  public Deployment execute(CommandContext commandContext) {
    DeploymentEntity deployment = deploymentBuilder.getDeployment();
    // deploy the Deployment
    persistDeployment(commandContext, deployment);
    // deploy the ProcessDefinition and fill cache
    commandContext.getProcessEngineConfiguration().getDeploymentManager().deploy(deployment);

    return deployment;
  }

  protected void persistDeployment(CommandContext commandContext, DeploymentEntity deployment) {
    deployment.setDeployTime(commandContext.getProcessEngineConfiguration().getEngineClock().now());

    // persist Deployment first, for DeploymentId
    commandContext.getProcessEngineConfiguration().getDeploymentEntityManager().insert(deployment);
    for (ResourceEntity resource : deployment.getResources()) {
      resource.setDeploymentId(deployment.getId());
    }

    // persist Resource
    commandContext.getProcessEngineConfiguration().getResourceEntityManager().batchInsert(deployment.getResources());
  }

}
